package com.ymatou.iapi.liveseller.testcase;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.liveseller.parameter.ActivityProductDto;
import com.ymatou.iapi.liveseller.parameter.ActivityProductListDto;
import com.ymatou.iapi.liveseller.parameter.CreateLiveActivityBean;
import com.ymatou.iapi.liveseller.parameter.CreateSellerLiveBean;
import com.ymatou.iapi.liveseller.parameter.LiveActivityDto;
import com.ymatou.iapi.liveseller.parameter.LiveActivityListBean;
import com.ymatou.iapi.liveseller.parameter.LiveActivityListDto;
import com.ymatou.iapi.liveseller.service.LiveActivityListCall;
import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.*;
import com.ymt.utils.tag.*;
import com.ymttest.business.service.LiveRoomCallService;
import com.ymttest.business.service.ProductManagerCallServiceV2;
import com.ymttest.database.model.LiveActivity;
import com.ymttest.database.model.LiveRoom;
import com.ymttest.database.model.YmtCatalogsI;
import com.ymttest.database.model.YmtProductActivityStock;
import com.ymttest.database.sqlwapper.LiveRoomWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.database.sqlwapper.YmtProductActivityStockWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;

/**
 * 直播活动列表 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_LiveActivityList {
	private static LiveActivityListBean liveactivitylistBean;
	private static LiveActivityListCall liveactivitylistCall;
	private static int sellerId = Integer.parseInt(EnvSetup.getData("autotest_seller1"));

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("直播活动列表");
	}

	@Before
	public void caseUp() {
		liveactivitylistBean = new LiveActivityListBean();
		liveactivitylistCall = new LiveActivityListCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(liveactivitylistCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	/**
	 * 验证商品
	 * @param aps
	 */
	private void verify(List<ActivityProductListDto> aps) {
		aps.forEach(activProd -> {
			List<YmtProductActivityStock> list;
			try {
				list = new YmtProductActivityStockWapper().selectByProductId(activProd.getProductId());
				Double max = list.stream().map(mapper -> mapper.getfActivityPrice()).max(Comparator.comparing(u -> u)).get();
				Double min = list.stream().map(mapper -> mapper.getfActivityPrice()).min(Comparator.comparing(u -> u)).get();
				Integer stock = list.stream().collect(Collectors.summingInt(YmtProductActivityStock::getIstocknum));
				Logger.verifyEquals(max, activProd.getMaxPrice(), "验证MaxPrice成功");
				Logger.verifyEquals(min, activProd.getMinPrice(), "验证MinPrice成功");
				Logger.verifyEquals(stock, activProd.getActivityStock(), "验证ActivityStock成功");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});

	}

	/**
	 * 验证活动
	 * @param la
	 */
	private void verify(LiveActivityListDto la) {
		try {
			LiveActivity alive = new LiveRoomWapper().selectLiveactivityById(la.getLiveActivityId());
			Logger.verifyEquals(alive.getLiveActivityId(), la.getLiveActivityId(), "验证LiveActivityId成功");
			Logger.verifyEquals((alive.getEndTime().getTime() - alive.getStartTime().getTime()) / 60000, la.getActivityMinuteLen(), "验证ActivityMinuteLen成功");
			int state = getActivityStatus(alive.getStartTime(), alive.getEndTime());
			Logger.verifyEquals(state, la.getActivityState(), "验证ActivityState成功");
			String text = getActivityStateText(la.getActivityState());
			Logger.verifyIsContains(text, la.getActivityStateText(), "验证ActivityStateText成功");
			// 有存储误差
			Logger.verifyEquals(alive.getEndTime().getTime() / 10000, la.getEndTime() / 10000, "验证EndTime成功");
			Logger.verifyEquals(alive.getStartTime().getTime() / 10000, la.getStartTime() / 10000, "验证StartTime成功");
			Logger.verifyEquals(alive.getLiveId(), la.getLiveId(), "验证liveid成功");
			Logger.verifyEquals(alive.getSellerId(), la.getSellerId(), "验证SellerId成功");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据开始和结束时间来判断当前直播的状态
	 * 
	 * @param start
	 * @param end
	 * @return
	 */
	private Integer getActivityStatus(Date start, Date end) {
		long now = System.currentTimeMillis();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(start);
		calendar.add(Calendar.SECOND, -30 * 60);
		long lockTime = calendar.getTime().getTime();
		if (now < lockTime) {
			return 4;
		} else if (now >= lockTime && now < start.getTime()) {
			return 3;
		} else if (now >= start.getTime() && now < end.getTime()) {
			return 2;
		} else if (now >= end.getTime()) {
			return 1;
		}
		return 0;
	}

	/**
	 * 根据直播状态获取回显字符
	 * 
	 * @param ActivityState
	 * @return
	 */
	private String getActivityStateText(Integer ActivityState) {
		String text = "";
		// 1已结束 2进行中 3即将开始 4 未开始
		if (ActivityState == 1) {
			text = "已结束";
		} else if (ActivityState == 2) {
			text = "进行中";
		} else if (ActivityState == 3) {
			text = "即将开始";
		} else if (ActivityState == 4) {
			text = "未开始";
		}
		return text;
	}
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_LiveActivityList_001() {
		Logger.start(true, "查询直播活动列表,成功");
		try {
			Logger.comment("创建商品");
			AddSellerProductRequest addpro = ProductManagerCallServiceV2.initAddSellerProductRequest(sellerId);
			String productId = ProductManagerCallServiceV2.addNewProduct(addpro).get("Data").getAsJsonObject().get("ProductId").getAsString();
			Logger.comment("创建直播");
			// 5分钟后开始200分钟后结束
			CreateSellerLiveBean clive = LiveRoomCallService.initCreatesellerliveBean(sellerId);
			Date now = YMTDateUtil.getDate();
			// 半小时之内会锁定不能修改
			Date starttime = new Date(now.getTime() + 60 * 60 * 1000);
			Date endtime = new Date(now.getTime() + 200 * 60 * 1000);
			clive.getLiveDto().setStartTime(YMTDateUtil.getFormatTime(starttime, YMTDateUtil.YMDHMS));
			
			LiveRoom createlive = LiveRoomCallService.CreateSellerLive(clive);
			Logger.comment("加入商品");
			LiveRoomCallService.AddProductsToLive(createlive.getId(), sellerId, productId);
			Logger.comment("查询商品规格");
			YmtCatalogsIWapper CIWapper = new YmtCatalogsIWapper();
			List<String> cids = CIWapper.selectCatalogsByProductId(productId).stream().map(YmtCatalogsI::getsCatalogId).collect(Collectors.toList());
			Logger.comment("创建秒杀活动");
			CreateLiveActivityBean createliveactivityBean = LiveRoomCallService.initCreateLiveActivityBean(createlive.getId(), cids.get(0), 5d, 6, starttime);
			LiveRoomCallService.CreateLiveActivity(createliveactivityBean);

			liveactivitylistBean.setLiveId(createlive.getId());
			liveactivitylistCall.setData(liveactivitylistBean);
			liveactivitylistCall.callService();
			Logger.verifyEquals("200", liveactivitylistCall.getString("Code"), "验证成功");
			liveactivitylistCall.getActivityProducts().forEach(aap -> {
				LiveActivityListDto la = aap.getLiveActivity();
				verify(la);
				List<ActivityProductListDto> aps = aap.getActivityProducts();
				verify(aps);

			});
		} catch (Exception e) {
			Logger.fail(e);
		}
	}


	@Test
	@Category({ P2.class })
	@TestCase
	public void Tc_LiveActivityList_002() {
		Logger.start(true, "不传参数liveid失败");
		try {
			liveactivitylistCall.setData(liveactivitylistBean);
			liveactivitylistCall.callService();
			Logger.verifyEquals("400", liveactivitylistCall.getString("Code"), "验证成功");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_LiveActivityList_003() {
		Logger.start(true, "查询直播活动列表,多规格,成功");
		try {
			Logger.comment("创建商品");
			AddSellerProductRequest addpro = ProductManagerCallServiceV2.initAddSellerProductRequest(sellerId);
			String productId = ProductManagerCallServiceV2.addNewProduct(addpro).get("Data").getAsJsonObject().get("ProductId").getAsString();
			Logger.comment("创建直播");
			// 5分钟后开始200分钟后结束
			CreateSellerLiveBean clive = LiveRoomCallService.initCreatesellerliveBean(sellerId);
			Date now = YMTDateUtil.getDate();
			// 半小时之内会锁定不能修改
			Date starttime = new Date(now.getTime() + 60 * 60 * 1000);
			Date endtime = new Date(now.getTime() + 200 * 60 * 1000);
			clive.getLiveDto().setStartTime(YMTDateUtil.getFormatTime(starttime, YMTDateUtil.YMDHMS));
			
			LiveRoom createlive = LiveRoomCallService.CreateSellerLive(clive);
			Logger.comment("加入商品");
			LiveRoomCallService.AddProductsToLive(createlive.getId(), sellerId, productId);
			Logger.comment("查询商品规格");
			YmtCatalogsIWapper CIWapper = new YmtCatalogsIWapper();
			List<String> cids = CIWapper.selectCatalogsByProductId(productId).stream().map(YmtCatalogsI::getsCatalogId).collect(Collectors.toList());
			Logger.comment("创建秒杀活动-多规格");
			CreateLiveActivityBean createliveactivityBean = LiveRoomCallService.initCreateLiveActivityBean(createlive.getId(), cids.get(0), 5d, 6, starttime);
			LiveActivityDto LiveActivity =createliveactivityBean.getLiveActivity();
			List<ActivityProductDto> ActivityProducts = new ArrayList<>();
			for (int i = 0; i < 2; i++) {
				ActivityProductDto apd = new ActivityProductDto();
				apd.setActivityPrice(5.0d*(i+1));
				apd.setActivityStock(10*(i+1));
				apd.setCatalogId(cids.get(i));
				apd.setProductId(productId);
				ActivityProducts.add(apd);
			}
			LiveActivity.setActivityProducts(ActivityProducts);
			LiveRoomCallService.CreateLiveActivity(createliveactivityBean);

			liveactivitylistBean.setLiveId(createlive.getId());
			liveactivitylistCall.setData(liveactivitylistBean);
			liveactivitylistCall.callService();
			Logger.verifyEquals("200", liveactivitylistCall.getString("Code"), "验证成功");
			liveactivitylistCall.getActivityProducts().forEach(aap -> {
				LiveActivityListDto la = aap.getLiveActivity();
				verify(la);
				List<ActivityProductListDto> aps = aap.getActivityProducts();
				verify(aps);

			});
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}